package com.xuan.chatroom.controller;

import com.xuan.chatroom.constants.Constant;
import com.xuan.chatroom.model.Result;
import com.xuan.chatroom.model.User;
import com.xuan.chatroom.service.UserService;
import com.xuan.chatroom.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    // 实现登录功能
    @RequestMapping("/login")
    public Result login(String username, String password, @RequestHeader(value = Constant.USER_TOKEN_HEADER, required = false) String token) {
        log.info("username: " + username + ", password: " + password);
        // 判断参数是否合法
        if(!StringUtils.hasLength(username) || !StringUtils.hasLength(password)) {
            return Result.fail("参数不合法");
        }

        return userService.verify(username, password, token);
    }


    // 实现注册功能
    @RequestMapping("/register")
    public Result register(String username, String password) {
        log.info("username: " + username + ", password: " + password);
        // 判断参数是否合法
        if(!StringUtils.hasLength(username) || !StringUtils.hasLength(password)) {
            return Result.fail("参数不合法");
        }
        return userService.register(username, password);
    }


    // 获取当前登录用户的信息
    @RequestMapping("/getUserInfo")
    public Result getUserInfo(@RequestHeader(Constant.USER_TOKEN_HEADER) String token) {
        // 从 token 获取用户信息
        Claims claims = JwtUtil.parseToken(token);
        int id = (int) claims.get(Constant.CLAIM_USERID);
        String username = (String) claims.get(Constant.CLAIM_USERNAME);
        return Result.success(new User(id, username, ""));
    }



    // 根据用户名搜索相关用户
    @RequestMapping("/searchUsers")
    public List<User> searchUsers(String username, @RequestHeader(Constant.USER_TOKEN_HEADER) String token) {
        log.info("username: " + username);
        if (!StringUtils.hasLength(username)) {
            return null;
        }

        Integer loginUserId = JwtUtil.getIdFromToken(token);
        return userService.searchUsers(username, loginUserId);
    }
}
